package com.w3c.pragmatic.utils;

import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * SFTP文件工具类
 *
 * @author wangdong
 */
@Slf4j
@Setter
@Getter
@Accessors(chain = true)
public class SftpUtil {

  /*private SftpAccountInfo info;

  public SFTPUtil(SftpAccountInfo info) {
    this.info = info;
  }

  *//**
   * 上传文件
   *
   * @param
   *//*
  public Session setupJsch() throws JSchException {
    JSch jsch = new JSch();
    Session jschSession = jsch.getSession(info.getUserName(), info.getServerIp(), info.getPort());
    jschSession.setPassword(info.getPassword());
    Properties config = new Properties();
    config.put("StrictHostKeyChecking", "no");
    jschSession.setConfig(config);
    jschSession.connect();
    return jschSession;
  }

  *//**
   * 影像件上传(尺寸这里固定)
   *
   * @param uploadDTOS 影像件列表
   * @param compress 是否需要压缩(true:是 false:否)
   *//*
  public void uploadFile(List<UploadDTO> uploadDTOS, boolean compress) {
    ChannelSftp channelSftp = null;
    Session session = null;
    try { // 根据用户名，主机ip，端口获取一个Session对象
      session = setupJsch();
      channelSftp = (ChannelSftp) session.openChannel("sftp");
      // 建立SFTP通道的连接
      channelSftp.connect();
      String directory = uploadDTOS.get(0).getTargetDirectory();
      // 创建目录
      createDir(directory, channelSftp);
      for (UploadDTO uploadDTO : uploadDTOS) {
        String fileName = uploadDTO.getTargetFileName();
        log.info("ftp上传文件开始正在上传. 路径: {},文件名:{}", directory, fileName);

        InputStream in;
        HttpURLConnection conn = null;
        ByteArrayOutputStream output = null;

        // 不同的文件来源不同的处理逻辑
        if (StringUtils.isNotBlank(uploadDTO.getSourceFileContent())) {
          // 这种压缩不处理
          byte[] contentBytes = uploadDTO.getSourceFileContent().getBytes(StringPool.UTF_8);
          in = new ByteArrayInputStream(contentBytes);
        } else {
          String sourceFileUrl = uploadDTO.getSourceFileUrl();
          // 图片类且打开压缩配置且大于2m
          String fileUrlWith2m =
              FundConstant.FILE_TYPE_IMAGE.equals(uploadDTO.getFileType())
                      && compress
                      && FileUtil.getFileSize(sourceFileUrl).compareTo(new BigDecimal(2)) > 0
                  ? sourceFileUrl + "?x-oss-process=image/resize,p_50"
                  : sourceFileUrl;
          conn = (HttpURLConnection) new URL(fileUrlWith2m).openConnection();
          conn.setRequestMethod("GET");
          conn.setConnectTimeout(20 * 1000);
          output = new ByteArrayOutputStream();
          IOUtils.copy(conn.getInputStream(), output);
          in = new ByteArrayInputStream(output.toByteArray());
        }

        channelSftp.put(in, fileName);

        in.close();
        FileUtil.closeIo(output);
        FileUtil.disconnect(conn);
        log.info("ftp上传文件上传成功. 路径: {},文件名:{}", directory, fileName);
      }
    } catch (Exception e) {
      log.warn("文件上传异常. file:{}", JSON.toJSONString(uploadDTOS), e);
      throw new HzlhException("文件上传异常" + e.getMessage());
    } finally {
      if (session != null && session.isConnected()) {
        session.disconnect();
      }
      if (channelSftp != null && channelSftp.isConnected()) {
        channelSftp.quit();
        channelSftp.disconnect();
      }
    }
  }

  *//**
   * 默认不压缩
   *
   * @param uploadDTOS
   *//*
  public void uploadFile(List<UploadDTO> uploadDTOS) {
    uploadFile(uploadDTOS, false);
  }

  *//**
   * 下载加密文件
   *
   * @param remotePathFile 远程文件，相对地址
   * @throws SftpException SftpException
   * @throws IOException IOException
   *//*
  public InputStream downloadFile(String remotePathFile) {
    ChannelSftp channel = null;
    Session session = null;
    try {
      // 打开SFTP通道
      session = setupJsch();
      channel = (ChannelSftp) session.openChannel("sftp");
      // 建立SFTP通道的连接
      channel.connect();
      // 账户可能存在账户目录
      if (StringUtils.isNotBlank(this.getInfo().getHomePath())) {
        remotePathFile = this.getInfo().getHomePath() + remotePathFile;
      }

      InputStream inputStream = channel.get(remotePathFile);

      final ByteArrayOutputStream output = new ByteArrayOutputStream();
      IOUtils.copy(inputStream, output);
      return new ByteArrayInputStream(output.toByteArray());
    } catch (JSchException e) {
      log.error("sftp异常,文件路径为:{}.失败原因为:{}", remotePathFile, e.getMessage());
      throw new HzlhException("sftp异常:" + e.getMessage());
    } catch (Exception e) {
      log.error("sftp下载文件异常,文件路径为:{}.失败原因为:{}", remotePathFile, e.getMessage());
      throw new HzlhException("sftp下载文件异常:" + e.getMessage());
    } finally {
      if (session != null && session.isConnected()) {
        session.disconnect();
      }
      if (channel != null && channel.isConnected()) {
        channel.quit();
        channel.disconnect();
      }
    }
  }

  *//**
   * 创建目录
   *
   * @param createpath
   * @return
   *//*
  public static boolean createDir(String createpath, ChannelSftp sftp) throws SftpException {
    try {
      if (isDirExist(createpath, sftp)) {
        sftp.cd(createpath);
        return true;
      }
      String pathArry[] = createpath.split("/");
      StringBuffer filePath = new StringBuffer("/");
      for (String path : pathArry) {
        if (path.equals("")) {
          continue;
        }
        filePath.append(path + "/");
        if (isDirExist(filePath.toString(), sftp)) {
          sftp.cd(filePath.toString());
        } else {
          // 建立目录
          sftp.mkdir(filePath.toString());
          // 进入并设置为当前目录
          sftp.cd(filePath.toString());
        }
      }
      return true;
    } catch (SftpException e) {
      throw e;
    }
  }

  *//**
   * 判断目录是否存在
   *
   * @param directory
   * @return
   *//*
  public static boolean isDirExist(String directory, ChannelSftp sftp) {
    boolean isDirExistFlag = false;
    try {
      SftpATTRS sftpATTRS = sftp.lstat(directory);
      isDirExistFlag = true;
      return sftpATTRS.isDir();
    } catch (Exception e) {
      if (e.getMessage().toLowerCase().equals("no such file")) {
        isDirExistFlag = false;
      }
    }
    return isDirExistFlag;
  }

  *//**
   * 下载文件
   *
   * @param path
   * @param remotePathFile
   * @param remoteOkFile
   * @return
   *//*
  public ByteArrayOutputStream downloadFile(
      String path, String remotePathFile, String remoteOkFile) {
    ChannelSftp channel = null;
    Session session = null;
    try {
      // 打开SFTP通道
      session = setupJsch();
      channel = (ChannelSftp) session.openChannel("sftp");
      // 建立SFTP通道的连接
      channel.connect();
      channel.cd(path);
      // 需要检验.ok文件是否存在，如果存在在进行下载
      SftpATTRS lstat = channel.lstat(remoteOkFile);
      InputStream inputStream = channel.get(remotePathFile);
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
      int len;
      byte[] bytes = new byte[1024];
      while ((len = inputStream.read(bytes)) != -1) {
        byteArrayOutputStream.write(bytes, 0, len);
      }
      return byteArrayOutputStream;
    } catch (JSchException e) {
      log.error("sftp异常,文件路径为：{}", remotePathFile, e);
      throw new HzlhException("sftp异常：" + e.getMessage());
    } catch (Exception e) {
      log.error("sftp下载文件异常,文件路径为：{}", remotePathFile, e);
      throw new HzlhException("sftp下载文件异常" + e.getMessage());
    } finally {
      if (session != null && session.isConnected()) {
        session.disconnect();
      }
      if (channel != null && channel.isConnected()) {
        channel.quit();
        channel.disconnect();
      }
    }
  }*/
}
